package com.fary.typehandle;

import cn.hutool.core.date.DateUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

/**
 * Date 类型存库
 */
@Component
@MappedTypes(Date.class)
@MappedJdbcTypes({JdbcType.CHAR, JdbcType.VARCHAR, JdbcType.NVARCHAR})
public class FormatDateTypeHandler extends BaseTypeHandler<Date> {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
        // 数据库存的字符串日期一般是 yyyy-MM-dd，统一转 yyyy-MM-dd 格式入库
        preparedStatement.setString(i, DateUtil.formatDate(date));
    }

    @Override
    public Date getNullableResult(ResultSet resultSet, String column) throws SQLException {
        return DateUtil.parse(resultSet.getString(column));
    }

    @Override
    public Date getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return DateUtil.parse(resultSet.getString(i));
    }

    @Override
    public Date getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return DateUtil.parse(callableStatement.getString(i));
    }
}
